<?php
// +----------------------------------------------------------------------
// | Name: 咪乐多管理系统 [ 为了快速搭建软件应用而生的，希望能够帮助到大家提高开发效率。 ]
// +----------------------------------------------------------------------
// | Copyright: (c) 2020~2021 https://www.lvacms.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed: 这是一个自由软件，允许对程序代码进行修改，但希望您留下原有的注释。
// +----------------------------------------------------------------------
// | Author: 西安咪乐多软件 <997786358@qq.com>
// +----------------------------------------------------------------------
// | Version: V1
// +----------------------------------------------------------------------

/**
 * @Name 服务
 * @Description
 * @Auther 西安咪乐多软件
 * @Date 2021/11/20 19:06
 */
namespace Modules\WritingAdmin\Services\Work;
use Illuminate\Support\Facades\DB;
use Modules\WritingAdmin\Models\WritingCollectionWork;
use Modules\WritingAdmin\Models\WritingWork;
use Modules\WritingAdmin\Models\WritingWorkTextbook;
use Modules\WritingAdmin\Services\BaseApiServices;
use Modules\Common\Exceptions\MessageData;
use Overtrue\Pinyin\Pinyin;

class WorkServices extends BaseApiServices
{
    public function index(array $data)
    {
        $model = WritingWork::query();
        $model = $this->setWhereQueryProject($model);
        $model = $this->queryCondition($model, $data, "title");
        if (isset($data['sort'])) {
            $model = $this->querySort($model, $data['sort']);
        }
        if(isset($data['author_id']) && $data['author_id'] > 0){
            $model = $model->where('author_id',$data['author_id']);
        }
        if(isset($data['dynasty_id']) && $data['dynasty_id'] > 0){
            $model = $model->where('dynasty_id',$data['dynasty_id']);
        }
        if(isset($data['allusion_id']) && $data['allusion_id'] > 0){
            $model = $model->where('allusion_id',$data['allusion_id']);
        }
        if(isset($data['anthology_id']) && $data['anthology_id'] > 0){
            $model = $model->where('anthology_id',$data['anthology_id']);
        }
        if(isset($data['theme_id']) && $data['theme_id'] > 0){
            $model = $model->where('theme_id',$data['theme_id']);
        }
        if(isset($data['brand_id']) && $data['brand_id'] > 0){
            $model = $model->where('brand_id',$data['brand_id']);
        }
        if(isset($data['geography_id']) && $data['geography_id'] > 0){
            $model = $model->where('geography_id',$data['geography_id']);
        }
        if(isset($data['famous_mountain_id']) && $data['famous_mountain_id'] > 0){
            $model = $model->where('famous_mountain_id',$data['famous_mountain_id']);
        }
        if(isset($data['city_id']) && $data['city_id'] > 0){
            $model = $model->where('city_id',$data['city_id']);
        }
        if(isset($data['time_m_id']) && $data['time_m_id'] > 0){
            $model = $model->where('time_m_id',$data['time_m_id']);
        }
        if(isset($data['describe_scenery_id']) && $data['describe_scenery_id'] > 0){
            $model = $model->where('describe_scenery_id',$data['describe_scenery_id']);
        }
        if(isset($data['festival_id']) && $data['festival_id'] > 0){
            $model = $model->where('festival_id',$data['festival_id']);
        }
        if(isset($data['solar_term_id']) && $data['solar_term_id'] > 0){
            $model = $model->where('solar_term_id',$data['solar_term_id']);
        }
        if(isset($data['season_id']) && $data['season_id'] > 0){
            $model = $model->where('season_id',$data['season_id']);
        }
        if(isset($data['flowers_plant_id']) && $data['flowers_plant_id'] > 0){
            $model = $model->where('flowers_plant_id',$data['flowers_plant_id']);
        }
        if(isset($data['textbook_id']) && $data['textbook_id'] > 0){
            $model = $model->whereHas('textbook_one',function($quest)use($data){
                $quest->where('textbook_id',$data['textbook_id']);
            });
        }
        if(isset($data['poem_book_id']) && $data['poem_book_id'] > 0){
            $model = $model->where('poem_book_id',$data['poem_book_id']);
        }
        $list = $model->select('id','title','author','dynasty','status','sort','baidu_wiki','created_at','updated_at')->orderBy('id', 'desc')
            ->paginate($data['limit'])->toArray();
        return $this->apiSuccess('', [
            'list' => $list['data'],
            'total' => $list['total']
        ]);
    }
    public function add(array $data)
    {
        $data = $this->getCommonId($data);
        DB::beginTransaction();
        try{
            $data['created_at'] = date('Y-m-d H:i:s');
            $textbook_to = [];
            if(count($data['textbook_to'])>0){
                $textbook_to = $data['textbook_to'];
            }
            unset($data['textbook_to']);
            $id = WritingWork::query()->insertGetId($data);
            $this->setWorkTextbook($textbook_to,$id);
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            $this->apiError('添加失败！');
        }
        return $this->apiSuccess('添加成功！');
    }
    private function setWorkTextbook($textbook_to,$id,$status = false){
        $date = date('Y-m-d H:i:s');
        if($status){
            WritingWorkTextbook::query()->where('work_id',$id)->delete();
        }
        foreach($textbook_to as $k=>$v){
            WritingWorkTextbook::query()->insert([
                'work_id'=>$id,
                'textbook_id'=>$v,
                'created_at'=>$date
            ]);
        }
    }
    public function edit(int $id)
    {
        $data = WritingWork::query()->with([
            'textbookTo'
        ])->find($id)?:$this->apiError(MessageData::GET_API_ERROR);
        $data = $data->toArray();
        if($data['textbook_to']){
            $data['textbook_to'] = array_column($data['textbook_to'],'id');
        }else{
            $data['textbook_to'] = [];
        }
        return $this->apiSuccess(MessageData::GET_API_SUCCESS,$data);
    }
    public function update(int $id,array $data)
    {
        DB::beginTransaction();
        try{
            $textbook_to = [];
            if(count($data['textbook_to'])>0){
                $textbook_to = $data['textbook_to'];
            }
            unset($data['textbook_to']);
            $data['updated_at'] = date('Y-m-d H:i:s');
            WritingWork::query()->where('id',$id)->update($data);
            $this->setWorkTextbook($textbook_to,$id,true);
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            $this->apiError('修改失败！');
        }
        return $this->apiSuccess('修改成功！');
    }
    public function status(int $id,array $data)
    {
        return $this->commonStatusUpdate(WritingWork::query(),$id,$data);
    }
    public function sorts(int $id,array $data)
    {
        return $this->commonSortsUpdate(WritingWork::query(),$id,$data);
    }
    public function del(int $id)
    {
        return $this->commonDestroy(WritingWork::query(),['id'=>$id]);
    }
    public function delAll(array $idArr)
    {
        return $this->commonDestroy(WritingWork::query(),$idArr);
    }



    public function getQuoteCardList($data){
        $model = WritingWork::query();
        $model = $model->where([
            'project_id'=>$data['project_id']
        ])->where('quote','!=',"");
        if(isset($data['noIds']) && count($data['noIds'])>0){
            $model = $model->whereIn('id',$data['noIds']);
        }
        $list = $model->select('id','title','title_tr','author','author_tr','dynasty','dynasty_tr','kind_cn','kind_cn_tr','quote','quote_tr')
            ->inRandomOrder()
            ->limit(10)
            ->get()
            ->toArray();
        return $this->apiSuccess('',$list);
    }



    public function getWorkList($data){
        $model = WritingWork::query()->select('id','title','title_tr','author','author_tr','dynasty','dynasty_tr','content','content_tr','quote','quote_tr');
        $model = $model->where(['project_id'=>$data['project_id'],'status'=>1]);
        if(isset($data['quote_status']) && $data['quote_status'] == 1){
            $model = $model->where('quote','!=','');
        }
        if (!empty($data['key'])){
            $model = $model->where('title','like','%' . $data['key'] . '%');
//            if(isset($data['status'])){
//                if($data['status'] == 1){
//                    $model = $model->where('title','like','%' . $data['key'] . '%');
//                    $model = $model->orWhere('title_tr','like','%' . $data['key'] . '%');
//                }else{
//                    $model = $model->where('content','like','%' . $data['key'] . '%');
//                    $model = $model->orWhere('content_tr','like','%' . $data['key'] . '%');
//                }
//            }else{
//                $model = $model->where('title','like','%' . $data['key'] . '%');
//                $model = $model->orWhere('title_tr','like','%' . $data['key'] . '%');
//                $model = $model->orWhere('content','like','%' . $data['key'] . '%');
//                $model = $model->orWhere('content_tr','like','%' . $data['key'] . '%');
//            }
        }
        if(isset($data['author_id']) && $data['author_id'] > 0){
            $model = $model->where('author_id',$data['author_id']);
        }
        if(isset($data['kind']) && $data['kind'] != ""){
            $model = $model->where('kind',$data['kind']);
        }
        if(isset($data['dynasty_id'])){
            $model = $model->whereIn('dynasty_id',explode(',',$data['dynasty_id']));
        }
        if(isset($data['anthology_id']) && $data['anthology_id'] > 0){
            $model = $model->where('anthology_id',$data['anthology_id']);
        }
        if(isset($data['theme_id']) && $data['theme_id'] > 0){
            $model = $model->where('theme_id',$data['theme_id']);
        }
        if(isset($data['brand_id']) && $data['brand_id'] > 0){
            $model = $model->where('brand_id',$data['brand_id']);
        }
        if(isset($data['geography_id']) && $data['geography_id'] > 0){
            $model = $model->where('geography_id',$data['geography_id']);
        }
        if(isset($data['famous_mountain_id']) && $data['famous_mountain_id'] > 0){
            $model = $model->where('famous_mountain_id',$data['famous_mountain_id']);
        }
        if(isset($data['city_id']) && $data['city_id'] > 0){
            $model = $model->where('city_id',$data['city_id']);
        }
        if(isset($data['time_m_id']) && $data['time_m_id'] > 0){
            $model = $model->where('time_m_id',$data['time_m_id']);
        }
        if(isset($data['describe_scenery_id']) && $data['describe_scenery_id'] > 0){
            $model = $model->where('describe_scenery_id',$data['describe_scenery_id']);
        }
        if(isset($data['festival_id']) && $data['festival_id'] > 0){
            $model = $model->where('festival_id',$data['festival_id']);
        }
        if(isset($data['solar_term_id']) && $data['solar_term_id'] > 0){
            $model = $model->whereIn('solar_term_id',explode(',',$data['solar_term_id']));
        }
        if(isset($data['season_id']) && $data['season_id'] > 0){
            $model = $model->where('season_id',$data['season_id']);
        }
        if(isset($data['flowers_plant_id']) && $data['flowers_plant_id'] > 0){
            $model = $model->where('flowers_plant_id',$data['flowers_plant_id']);
        }
        if(isset($data['textbook_id'])){
            $model = $model->whereHas('textbook_one',function($quest)use($data){
                $quest->whereIn('textbook_id',explode(',',$data['textbook_id']));
            });
        }
        if(isset($data['poem_book_id']) && $data['poem_book_id'] > 0){
            $model = $model->where('poem_book_id',$data['poem_book_id']);
        }
        $list = $model->orderBy('sort','asc')
            ->orderBy('id','desc')
            ->paginate($data['limit'])->toArray();
        return $this->apiSuccess('', [
            'list' => $list['data'],
            'total' => $list['total']
        ]);
    }

    private function strSplitUnicode($str, $l = 0) {
        if ($l > 0) {
            $ret = array();
            $len = mb_strlen($str, "UTF-8");
            for ($i = 0; $i < $len; $i += $l) {
                $ret[] = mb_substr($str, $i, $l, "UTF-8");
            }
            return $ret;
        }
        return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    }

    private function getTitleStr($str){
        if(!$str){
            return [];
        }
        $str = str_replace(" ","",str_replace(" ","",trim($str)));
        // 标题数组
        $strList = $this->strSplitUnicode($str);
        $pinyin = new Pinyin();
        // 标题拼音数组
        $arrPinyin = $pinyin->convert($str,PINYIN_TONE);
        $arr = [];
        $count = 0;
        foreach ($strList as $k=>$v){
            if (!in_array($v,["·"," ","《","》","）","（","，","。","，","◎","；","？","：","“","”","！","「","」","『","』"])){
                $arr[] = [
                    "pinyin"=>isset($arrPinyin[$count])?$arrPinyin[$count]:'',
                    "value"=>$v,
                ];
                $count = $count + 1;
            }else{
                $arr[] = [
                    "pinyin"=>"",
                    "value"=>$v,
                ];
            }
        }
        return $arr;
    }


    public function getWorkDetails($data){
        if(!isset($data['id']) || $data['id'] <= 0){
            $this->apiError('缺少或错误参数id');
        }
        $info = WritingWork::query()->select('id','title','title_tr','author_id','author','author_tr','dynasty','dynasty_tr','content','content_tr','intro','intro_tr','annotation','annotation_tr','translation','translation_tr','master_comment','master_comment_tr','quote','quote_tr')->where(['project_id'=>$data['project_id'],'status'=>1,'id'=>$data['id']])->first();
        if(!$info){
            $this->apiError('暂无数据');
        }
        $info = $info->toArray();

        $info['title_arr'] = $this->getTitleStr($info['title']);
        $info['author_arr'] = $this->getTitleStr($info['author']);
        $info['dynasty_arr'] = $this->getTitleStr($info['dynasty']);
        $info['content_arr'] = explode("\n",str_replace("\r","",$info['content']));
        $arr = [];
        foreach ($info['content_arr'] as $k=>$v){
            $arr[] = $this->getTitleStr($v);
        }
        $info['content_arr'] = $arr;
        $info['collection_status'] = false;
        if(isset($data['user_id']) && $data['user_id'] > 0) {
            $id = WritingCollectionWork::query()->where(['user_id' => $data['user_id'],'work_id'=>$data['id']])->value('id');
            if ($id) {
                $info['collection_status'] = true;
            }
        }
        return $this->apiSuccess('',$info);
    }
}
